<?php

namespace App\Admin\Controllers;
use App\Models\Company;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Widgets\Form as myForm;
use Illuminate\Http\Request;

class ConfigController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('币种管理');
            $content->description('');

            $content->body($this->form());
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $currency = json_decode(((\DB::table('admin_config')->where('name','currency')->first())->value));
        $content = "<button type='button' class='btn' data-toggle='modal' data-target='#myModal' >新增币种</button><table class='table'><tr><th>币种</th><th>名称</th><th>汇率</th><th>操作</th></tr>";
        foreach($currency as $k=>$v){
            $edit = $k == "CNY"?"":'<button type="button" class="btn" data-toggle="modal" data-target="#myModal" id="" data-key="'.$k.'" data-name="'.$v->value.'" data-exchange="'.$v->exchange.'">编辑</button> <button type="button" class="btn btn-danger" onclick="delDom(\''.$k.'\')">删除</button>';
            $content.="<tr id='c-$k'><td>$k</td><td>$v->value</td><td>$v->exchange</td><td>$edit</td></tr>";
        }
        $content .='</table><div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        <form action="" method="post">
          <div class="form-group">
            <label for="currency-key" class="control-label key">币种:</label>
            <input type="text" class="form-control" id="currency-key">
          </div>
          <div class="form-group">
            <label for="currency-name" class="control-label name">名称:</label>
            <input type="text" class="form-control" id="currency-name">
          </div>
          <div class="form-group">
            <label for="currency-exchange" class="control-label exchange">汇率:</label>
            <input type="number" class="form-control" id="currency-exchange">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" id="st" class="btn btn-primary">提交</button>
      </div>
    </div>
  </div>
</div>
<button type="button" id="stAll" class="btn btn-primary">保存</button>
';
$content.=<<<EOD
<script>
$('#myModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget)
  var exchange = button.data('exchange')
  var name = button.data('name')
  var key = button.data('key')
  var modal = $(this)
  modal.find('.modal-title').text('修改' + name)
  modal.find('#currency-exchange').val(exchange)
  modal.find('#currency-name').val(name)
  modal.find('#currency-key').val(key)
})

$('#st').on('click',function(){
    var key = $('#currency-key').val()
    var name = $('#currency-name').val()
    var exchange = $('#currency-exchange').val()
    $('#c-'+key).remove();
    $('table tr:eq(0)').after($('<tr id="c-'+key+'"><td>'+key+'</td><td>'+name+'</td><td>'+exchange+'</td><td><button type="button" class="btn" data-toggle="modal" data-target="#myModal"  data-key="'+key+'" data-name="'+name+'" data-exchange="'+exchange+'">编辑</button> <button type="button" class="btn btn-danger" onclick="delDom(\''+key+'\')">删除</button></td></tr>'));
    $('#myModal').modal('hide');
});
$('#stAll').on('click',function(){
    var array = {};
    var head = $("th");
    $(".table tr").each(function () {
        if(this.getAttribute('id') && this.getAttribute('id').split("-")[0]=='c'){
            var key = this.getAttribute('id').split("-")[1]
            var json = {};
            $(this).find("td").each(function (i) {
                switch(i){
                    case 1:
                    json['value'] = $(this).html();
                    break;
                    case 2:
                    json['exchange'] = $(this).html();
                    break;
                    default:
                    break;
                }

            });
            array[key] = json;
        }
    });
    $.ajax({
        method: "POST",
        url: "/admin/sysConfig/setJson",
        data: array
    }).success(function( msg ) {
        if(msg.msg){
            alert("json 解析错误，保存失败")
        }else{
            alert("保存成功");
        }
    });

});
function delDom(v){
    $('#c-'+v).remove();
}
</script>
EOD;
        return $content;
    }

    public function setJson(Request $req){
        if( $j  = json_encode($req->all()) ){
            \DB::table('admin_config')->where('name','currency')->update(['value'=>$j]);
            return json_encode(['msg'=>0])  ;
        }else{
            return json_encode(['msg'=>1]);
        }
    }
}
